<template>
  <div class="update-container">
    <img class="img" :src="img" ref="img" />
    <div class="tool-bar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
// 图片裁剪js
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  props: {
    img: {
      required: true,
      type: [String, Object]
    }
  },
  data () {
    return {
      cropper: null // 整个裁剪js的实例
    }
  },
  // 组件加载，操作dom用这个生命周期函数
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false
    })
  },
  methods: {
    onConfirm () {
      // 基于服务端的裁切使用 getData 方法获取裁切参数
      // console.log(this.cropper.getData())
      // 纯客户端的裁切使用 getCropperCanvas 获取裁切的文件对象
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        this.updateUserPhoto(blob)
      })
    },
    async updateUserPhoto (blob) {
      this.$toast.loading({
        message: '保存中', // 提示内容
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续时间
      })
      try {
        // 如果接口要求 Content-Type 是 multipart/form-data
        // 则你必须传递 FormData 对象
        const formData = new FormData()
        formData.append('photo', blob)
        const { data } = await updateUserPhoto(formData)
        // 关闭弹窗
        this.$emit('close')
        // 更新视图
        this.$emit('update-photo', data.data.photo)
        // 弹窗提示
        this.$toast.success('更新成功')
      } catch (err) {
        // 更新失败
        // console.log(err)
        this.$toast('更新失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.update-container{
  width: 100%;
  height: 100%;
  background-color: #000;
}
img{
  max-width: 100%;
  display: block;
}
.tool-bar{
  position: absolute;
  left: 25px;
  right: 25px;
  bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 20px;
  color: #fff;
}
</style>
